package com.power.algorithm.structure.array;


import lombok.extern.slf4j.Slf4j;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.ArrayList;
import java.util.Arrays;

/**
 * 1. 创建一个数组提供以下方法
 * 2. 增加一个元素
 * 3. 删除一个元素
 * 4. 修改一个元素
 * 5. 查找一个元素
 * 1. 使用二分查找
 * 2. 使用顺序查找
 * 3. 。。。
 * 6. 对数组进行排序
 * 1. 快速排序
 * 2. 排序算法
 */
@Slf4j
public class PowerArray {
    private final Logger logger = LoggerFactory.getLogger(PowerArray.class);
    private int CAPACITY = 10;
    private int INDEX = 0;
    private static final float EXPENSION_FACTORY = 1.5f;
    public Object[] array;
    private int size;


    public PowerArray() {
        //如果容量充足，则添加元素
        if (array == null) {
            array = new Object[CAPACITY];
        }
    }

    //自动扩容
    public  Object[] expension(Object[] origin_array) {
        int capacity = Math.round(CAPACITY * EXPENSION_FACTORY);
        return Arrays.copyOf(origin_array, capacity);
    }


    // 添加一个元素
    public  void add(Object obj) {
        if (size < CAPACITY) {
            array[INDEX++] = obj;
        } else {
            //扩容
            array = expension(array);
            array[INDEX++] = obj;
        }
        size++;
    }

    public String outOfBoundMsg(int index) {
        return "index " + index + "  size  " + size;
    }

    //检查索引是否越界
    public void checkIndexBound(int index) {
        if (index < 0 || index > size) {
            throw new IndexOutOfBoundsException(outOfBoundMsg(index));
        }
    }

    //todo
    //删除一个元素
    public void remove(int index) {
        checkIndexBound(index);
        int movednum = size - index - 1;
        System.arraycopy(array, index + 1, array, index, movednum);
        size--;
    }

    //更新一个元素
    public void update(Object element) throws Exception {
        try {
            //注意边界条件 不能越过数组
            for (int i = 0; i < size; i++) {
                if (element.equals(array[i])) {
                    array[i] = element;
                }
            }
        } catch (IndexOutOfBoundsException e) {
            logger.error("Index out of bound {}", e.getCause());
        }

    }

    //todo
    //查找一个元素，返回索引
    public int get(Object element) {
        for (int i = 0; i < array.length; i++) {
            if (array[i] == element) {
                return i;
            }
        }
        return -1;
    }


    //
    public int size() {
        return size;
    }

    public static void main(String[] args) {
        PowerArray powerArray = new PowerArray();
        for (int i = 0; i < 7; i++) {
            powerArray.add(i);
        }


        for (int i = 0; i < powerArray.size; i++) {
            System.out.println(powerArray.array[i]);
        }
        System.out.println("array size()长度" + powerArray.size());
        ArrayList arrayList = new ArrayList();
    }
}
